import { useEffect } from 'react';
import type { Emitter, EventType, Handler } from 'mitt';
import type { IDanmakuRendererEvent } from '@/compnents';

export type UseEventListener<Events extends Record<EventType, unknown>> = <Key extends keyof Events = keyof Events, Event = Events[Key]>(
  envet?: Emitter<Events>,
  eventName?: Key,
  handler?: Handler<Event>,
) => void;

export const useEventListener: UseEventListener<any> = (event, eventName, listener) => {
  useEffect(() => {
    if (!event || !eventName || typeof listener !== 'function') {
      return () => {};
    }
    event.on(eventName, listener);
    return () => {
      event.off(eventName, listener);
    };
  }, [event, eventName, listener]);
};

export const useDanmakuRendererEventListener: UseEventListener<IDanmakuRendererEvent> = useEventListener;
